package com.qb.hotelTV.viewmodel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.LiveData;

import com.qb.hotelTV.base.BaseViewModel;
import com.qb.hotelTV.repository.TvRepository;
import com.qb.hotelTV.Model.VideoModel;
import com.qb.hotelTV.Model.ApkModel;
import com.qb.hotelTV.Model.RoomMessageModel;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页ViewModel
 * 管理首页的所有业务逻辑和数据状态
 */
public class IndexViewModel extends BaseViewModel {
    private static final String TAG = "IndexViewModel";
    
    private TvRepository repository;
    
    // 频道相关数据
    private MutableLiveData<ArrayList<VideoModel>> _tvChannels = new MutableLiveData<>();
    public LiveData<ArrayList<VideoModel>> tvChannels = _tvChannels;
    
    private MutableLiveData<VideoModel> _currentChannel = new MutableLiveData<>();
    public LiveData<VideoModel> currentChannel = _currentChannel;
    
    // 房间信息
    private MutableLiveData<RoomMessageModel> _roomMessage = new MutableLiveData<>();
    public LiveData<RoomMessageModel> roomMessage = _roomMessage;
    
    // 应用列表
    private MutableLiveData<ArrayList<ApkModel>> _apkList = new MutableLiveData<>();
    public LiveData<ArrayList<ApkModel>> apkList = _apkList;
    
    // 配置状态
    private MutableLiveData<Boolean> _isConfigured = new MutableLiveData<>();
    public LiveData<Boolean> isConfigured = _isConfigured;
    
    // 视频播放状态
    private MutableLiveData<Boolean> _isVideoPlaying = new MutableLiveData<>();
    public LiveData<Boolean> isVideoPlaying = _isVideoPlaying;
    
    // 加载状态
    private MutableLiveData<Boolean> _isChannelsLoading = new MutableLiveData<>();
    public LiveData<Boolean> isChannelsLoading = _isChannelsLoading;
    
    private MutableLiveData<Boolean> _isRoomLoading = new MutableLiveData<>();
    public LiveData<Boolean> isRoomLoading = _isRoomLoading;
    
    public IndexViewModel(@NonNull Application application) {
        super();
        repository = TvRepository.getInstance(application);
        checkConfiguration();
    }
    
    /**
     * 检查配置状态
     */
    public void checkConfiguration() {
        boolean configured = !repository.isFirstRun() && 
                           !repository.getServerAddress().isEmpty() && 
                           !repository.getTenant().isEmpty();
        _isConfigured.setValue(configured);
        
        if (configured) {
            loadInitialData();
        }
    }
    
    /**
     * 保存配置
     */
    public void saveConfiguration(String serverAddress, String roomNumber, String tenant) {
        if (serverAddress.isEmpty() || roomNumber.isEmpty() || tenant.isEmpty()) {
            showError("请填写完整的配置信息");
            return;
        }
        
        repository.saveConfiguration(serverAddress, roomNumber, tenant);
        _isConfigured.setValue(true);
        showToast("配置保存成功");
        
        // 加载数据
        loadInitialData();
    }
    
    /**
     * 加载初始数据
     */
    private void loadInitialData() {
        loadTvChannels();
        loadRoomMessage();
        loadApkList();
    }
    
    /**
     * 加载TV频道
     */
    public void loadTvChannels() {
        _isChannelsLoading.setValue(true);
        
        addDisposable(
            repository.getTvChannels()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    channels -> {
                        _isChannelsLoading.setValue(false);
                        _tvChannels.setValue(channels);
                        
                        // 自动选择第一个频道
                        if (!channels.isEmpty()) {
                            selectChannel(channels.get(0));
                        }
                        
                        Log.d(TAG, "频道数据加载成功，共" + channels.size() + "个频道");
                    },
                    error -> {
                        _isChannelsLoading.setValue(false);
                        showError("频道数据加载失败: " + error.getMessage());
                        Log.e(TAG, "频道数据加载失败", error);
                    }
                )
        );
    }
    
    /**
     * 刷新频道数据
     */
    public void refreshChannels() {
        _isChannelsLoading.setValue(true);
        
        addDisposable(
            repository.refreshChannels()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    channels -> {
                        _isChannelsLoading.setValue(false);
                        _tvChannels.setValue(channels);
                        showToast("频道数据刷新成功");
                    },
                    error -> {
                        _isChannelsLoading.setValue(false);
                        showError("刷新失败: " + error.getMessage());
                    }
                )
        );
    }
    
    /**
     * 加载房间信息
     */
    public void loadRoomMessage() {
        _isRoomLoading.setValue(true);
        
        addDisposable(
            repository.getRoomMessage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    roomMsg -> {
                        _isRoomLoading.setValue(false);
                        _roomMessage.setValue(roomMsg);
                        Log.d(TAG, "房间信息加载成功");
                    },
                    error -> {
                        _isRoomLoading.setValue(false);
                        Log.w(TAG, "房间信息加载失败: " + error.getMessage());
                        // 房间信息失败不显示错误，因为不是必需的
                    }
                )
        );
    }
    
    /**
     * 加载应用列表
     */
    public void loadApkList() {
        addDisposable(
            repository.getApkList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    apks -> {
                        _apkList.setValue(apks);
                        Log.d(TAG, "应用列表加载成功，共" + apks.size() + "个应用");
                    },
                    error -> {
                        Log.w(TAG, "应用列表加载失败: " + error.getMessage());
                        // 应用列表失败不显示错误，因为不是必需的
                    }
                )
        );
    }
    
    /**
     * 选择频道
     */
    public void selectChannel(VideoModel channel) {
        if (channel != null) {
            _currentChannel.setValue(channel);
            _isVideoPlaying.setValue(true);
            Log.d(TAG, "选择频道: " + channel.getStreamName());
        }
    }
    
    /**
     * 切换到下一个频道
     */
    public void nextChannel() {
        ArrayList<VideoModel> channels = _tvChannels.getValue();
        VideoModel current = _currentChannel.getValue();
        
        if (channels != null && !channels.isEmpty() && current != null) {
            int currentIndex = channels.indexOf(current);
            int nextIndex = (currentIndex + 1) % channels.size();
            selectChannel(channels.get(nextIndex));
        }
    }
    
    /**
     * 切换到上一个频道
     */
    public void previousChannel() {
        ArrayList<VideoModel> channels = _tvChannels.getValue();
        VideoModel current = _currentChannel.getValue();
        
        if (channels != null && !channels.isEmpty() && current != null) {
            int currentIndex = channels.indexOf(current);
            int prevIndex = (currentIndex - 1 + channels.size()) % channels.size();
            selectChannel(channels.get(prevIndex));
        }
    }
    
    /**
     * 根据名称查找频道
     */
    public void selectChannelByName(String channelName) {
        ArrayList<VideoModel> channels = _tvChannels.getValue();
        if (channels != null) {
            for (VideoModel channel : channels) {
                if (channel.getStreamName().contains(channelName)) {
                    selectChannel(channel);
                    return;
                }
            }
        }
        showToast("未找到频道: " + channelName);
    }
    
    /**
     * 暂停视频
     */
    public void pauseVideo() {
        _isVideoPlaying.setValue(false);
    }
    
    /**
     * 播放视频
     */
    public void playVideo() {
        _isVideoPlaying.setValue(true);
    }
    
    /**
     * 停止视频
     */
    public void stopVideo() {
        _isVideoPlaying.setValue(false);
        _currentChannel.setValue(null);
    }
    
    /**
     * 获取当前配置
     */
    public String getServerAddress() {
        return repository.getServerAddress();
    }
    
    public String getRoomNumber() {
        return repository.getRoomNumber();
    }
    
    public String getTenant() {
        return repository.getTenant();
    }
} 